package net.portly.cst.flex;

import java.io.Serializable;

import net.portly.cst.AssetIdType;
import net.portly.cst.StructuralAssetInstance;

import com.fatwire.rest.beans.Attribute;
import com.fatwire.rest.beans.Struct;

public class FlexAssetAttribute implements Comparable<FlexAssetAttribute>, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private boolean required;
	private AssetIdType assetIdType;
	private int ordinal;
	private StructuralAssetInstance structuralAssetInstance;
	
	public FlexAssetAttribute(Struct item) {
		for (Attribute innerAttr :  item.getItems()) {
			String name = innerAttr.getName();
			if ("required".equals(name)) {
				setRequired(innerAttr.getData().getStringValue());
			} else {
				if ("ordinal".equals(name)) {
					setOrdinal(innerAttr.getData().getIntegerValue());
				} else {
					if ("assetid".equals(name)) {
						setAssetIdType(innerAttr.getData().getStringValue());
					}
				}
			}
		}
	}

	private void setRequired(String stringValue) {
		setRequired(new Boolean(stringValue));
	}

	public void setRequired(boolean value) {
		required = value;
	}

	public boolean isRequired() {
		return required;
	}

	public void setAssetIdType(String stringValue) {
		this.assetIdType = new AssetIdType (stringValue);
	}

	public AssetIdType getAssetIdType() {
		return assetIdType;
	}

	public void setOrdinal(int intValue) {
		this.ordinal = intValue;
	}

	public int getOrdinal() {
		return ordinal;
	}

	public String toString() {
		String instanceString = getStructuralAssetInstanceToString();
		return "id:type: " + assetIdType + instanceString + " ordinal: " + ordinal+ " required: " +required;
	}

	private String getStructuralAssetInstanceToString() {
		if (structuralAssetInstance == null)
			return "";
		return " ( name: " + structuralAssetInstance.getName() + " ) ";
	}

	public StructuralAssetInstance getStructuralAssetInstance() {
		return structuralAssetInstance;
	}

	public void setStructuralAssetInstance(StructuralAssetInstance structuralAssetInstance) {
		this.structuralAssetInstance = structuralAssetInstance;
	}

	/**
	 * compareTo uses ordinal to determine sort sequence
	 */
	public int compareTo(FlexAssetAttribute compObj) {
		if (compObj == null)
			return -1;
		if (compObj.getOrdinal() > this.getOrdinal())
			return -1;
		else
			if (compObj.getOrdinal() < this.getOrdinal())
				return 1;
		
		return 0;
	}
}
